<?php

namespace addons\facrm\controller\facrm\product;

use addons\facrm\library\BackendApi;

use app\admin\model\facrm\product\Type;
use app\admin\model\facrm\product\Unit;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品信息
 * @icon fa fa-circle-o
 */
class Product extends BackendApi {

    /**
     * Product模型对象
     * @var \app\admin\model\facrm\product\Product
     */
    protected $model = null;
    protected $distinguish = true;
    protected $searchFields = 'id,name,specification,sku,prop';
    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\product\Product;
        $this->request->filter(['strip_tags']);
    }
    /**
     * 产品列表
     * @ApiBody ("参数参考电脑版")
     */
    public function index()
    {

        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array("rows" => $list);

        return $this->success('', $result);
    }
    /**
     * 添加商品
     * @ApiMethod (POST)
     * @ApiParams(name="name", type="string", required=true, description="商品名称")
     * @ApiParams(name="product_type_id", type="int", required=true, description="分类ID")
     * @ApiParams(name="product_unit_id", type="int", required=true, description="单位id")
     * @ApiParams(name="unit", type="int", required=true, description="单位名称")
     * @ApiParams(name="specification", type="string", required=true, description="规格")
     * @ApiParams(name="sku", type="string", required=false, description="编码")
     * @ApiParams(name="inventory", type="int", required=false, description="库存")
     * @ApiParams(name="price", type="int", required=false, description="价格")
     * @ApiParams(name="remark", type="string", required=false, description="商品说明")
     * @ApiBody ("其它参数参考电脑版,去掉row,取里面的")
     */
    public function add()
    {

        $params = $this->request->post();
        if ($params) {
            $result = false;
            Db::startTrans();
            try {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $result = $this->model->validateFailException(true)->validate($name . '.add')->allowField(true)->isUpdate(false)->save($params);
                Db::commit();
            } catch (ValidateException $e) {

                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }

    /**
     * 修改商品
     * @ApiMethod (POST|GET)
     * @ApiParams(name="id", type="int", required=true, description="商品id")
     * @ApiParams(name="name", type="string", required=true, description="商品名称")
     * @ApiParams(name="product_type_id", type="int", required=true, description="分类ID")
     * @ApiParams(name="product_unit_id", type="int", required=true, description="单位id")
     * @ApiParams(name="unit", type="int", required=true, description="单位名称")
     * @ApiParams(name="specification", type="string", required=true, description="规格")
     * @ApiParams(name="sku", type="string", required=false, description="编码")
     * @ApiParams(name="inventory", type="int", required=false, description="库存")
     * @ApiParams(name="price", type="int", required=false, description="价格")
     * @ApiParams(name="remark", type="string", required=false, description="商品说明")
     * @ApiBody ("其它参数参考电脑版,去掉row,取里面的")
     */
    public function edit()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }


        if ($this->request->isPost()) {

            $params = $this->request->post();
            if ($params) {
                $result = false;
                Db::startTrans();

                try {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $row->validateFailException(true)->validate($name . '.edit');
                    $result = $row->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->success('', $row);

    }
    /**
     * 删除商品
     * @param string $ids
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 获取商品类型列表
     */
    public function get_type_list() {
        $this->model = new \app\admin\model\facrm\product\Type;
        $this->selectpage();

    }

    /**
     * 获取当前商品选择类型的属性
     * @param string $type_id 类型ID
     */
    public function get_type_prop() {
        $type_id = $this->request->param('type_id');
        if (!$type_id) $this->error(__("类型ID错误"));
        $type = new Type();
        $list = $type
            ->field("prop")
            ->where('id', $type_id)
            ->find();
        $this->success("",$list);
    }


    /**
     * 获取单位列表
     */
    public function get_unit_list($keyValue='') {
        $this->model = new \app\admin\model\facrm\product\Unit();
        $this->selectpage();
    }

}
